package com.enterprise.support.utility;

import com.enterprise.application.mvc.struts.view.freemarker.BeanWrapper;
import freemarker.template.Template;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.HashMap;
import java.util.Locale;

/**
 * Created by IntelliJ IDEA.
 * User: Zhanggaojiang
 * Date: 11-1-19
 * Time: 上午9:26
 * Email: z82422@gmail.com
 * 根据 Ftl 模板 生成文档
 */
public class FreemarkerUtility {
    private final static Logger logger = Logger.getLogger(FreemarkerUtility.class);
    private final static freemarker.template.Configuration configuration = new freemarker.template.Configuration();

    static {
        try {
            configuration.setDirectoryForTemplateLoading(new File(Configuration.ConfHomeDirectory).getParentFile());
            //configuration.setClassForTemplateLoading(FreemarkerUtility.class, "/");
            configuration.setObjectWrapper(new BeanWrapper());
            configuration.setDefaultEncoding("UTF-8");
            configuration.setTemplateUpdateDelay(0);
            configuration.setEncoding(Locale.CHINA, "UTF-8");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static boolean builerTemplate(String templateFile, final Enterprise params, String savepath) {

        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateFile);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(savepath),"UTF-8"));
            template.process(new HashMap() {{
                put("input", params);
            }}, out);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                out.flush();
                out.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return true;
    }

    public static void main(String[] args) {
        FreemarkerUtility.builerTemplate("Entity.ftl", new Enterprise(), "E:\\MY_PROJECT\\enterprise_tools\\java\\src\\config\\tools\\entity2.ftl");
    }
}

